<?php

namespace services\models;

use Yii;

/**
 * This is the model class for table "iliketry.member_score".
 *
 * @property integer $member_no
 * @property integer $score
 * @property string $xm
 * @property integer $addtime
 * @property integer $is_all
 * @property integer $type
 */
class MemberScore extends \common\models\MemberScore
{

    public static $IS_ALL_SURPLUS = 0;
    public static $IS_ALL_NOT_SURPLUS = 1;
    public function beforeSave($insert)
    {

        if($insert){
            $this->addtime = time();
        }

        return parent::beforeSave($insert);
    }

    /*
     * 更新用户试豆redis
     * */
    public function afterSave($insert, $changedAttributes){

        Yii::$app->redis->incrby('U_score_' . $this->member_no, $this->score);
        Yii::$app->redis_old->hincrby('M_' . $this->member_no, 'sumscore', $this->score);
        parent::afterSave($insert, $changedAttributes);
        //var_dump(Yii::$app->redis->get('U_score_' . self::$_instance->member_no));
    }


    /**
     * 增加用户试豆
     * 在试豆表增加一条记录
     * 试豆数为正数为增加试豆.
     * 试豆数为负数为扣除试豆.
     * @param $score int 试豆
     * @param $xm string 操作说明
     * @param $uid int 用户id
     * @return mixed
     */
    public static function addScore($score, $xm, $uid, $type=1)
    {
        $_instance = new static;


        $_instance->xm = $xm;
        $_instance->score = $score;
        $_instance->member_no = $uid;
        $_instance->is_all = $type;
        return $_instance->save();
    }

    /**
     * 扣除用户试豆
     * 在试豆表增加一条记录
     * 试豆数为正数为扣除试豆.
     * @param $score int 试豆
     * @param $xm string 操作说明
     * @param $uid int 用户id
     * @return mixed
     */
    public static function subScore($score, $xm, $uid, $type = 1)
    {
        return static::addScore(-$score, $xm, $uid, $type);
    }

    /**
     * @param $uid integer liketry用户ID
     * @return integer
     * @throws \yii\base\Exception
     */
    public static function getScoreFromMemberInfoNo($uid)
    {
        if (empty($uid) || !is_numeric($uid)) {
            throw new \yii\base\Exception('$uid type is Integer, greater than 0');
        }
        return (int)static::find()->where(['member_no' => $uid])->sum('score');
    }

    public static function getScore($member_no)
    {
        return (int)static::find()->where(['member_no' => $member_no])->sum('score');
    }


}
